package com.htgd.gardenexpo.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *高德工具接口
 * @author lihailong
 * @date
 */
@Component
public class GaoDeUtils {

    @Value("${gaode.city}")
    private String city;

    @Value("${gaode.key}")
    private String key;


    public JSONObject getWeather(){

        JSONObject weatherData = null;
        try {
            // 创建URL对象并设置API的请求URL
            URL url = new URL("https://restapi.amap.com/v3/weather/weatherInfo?city="+city+"&key="+key+"&extensions=base&output=JSON");
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法
            connection.setRequestMethod("GET");

            // 获取输入流并读取数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 关闭连接
            connection.disconnect();
            // 处理JSON数据
            weatherData = JSON.parseObject(response.toString());
            JSONArray lives = weatherData.getJSONArray("lives");
            JSONObject weather = (JSONObject) JSONObject.parse(lives.get(0).toString());
            return weather;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return weatherData;
    }

    public static void main(String args[]){
//        JSONObject weather = getWeather();
//        System.out.println(weather);
    }
}
